package com.ruoyi.web.controller.wnjk.app.login;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.interceptor.loginInterceptor.AuthenticationContextHolder;
import com.ruoyi.framework.interceptor.loginInterceptor.JwtUtil;
import com.ruoyi.system.wnjk.domain.po.WnjkUser;
import com.ruoyi.system.wnjk.service.IWnjkUserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/app/user")
public class AppUserLoginController {
    @Autowired
    private IWnjkUserService wnjkUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${jwt.expiration:86400000}")
    private long jwtExpiration;



    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String, String> map) {
        if (map.get("phone") == null || map.get("password") == null) {
            return AjaxResult.error("电话或密码不能为空");
        }
        if (map.get("password").length() < 6) {
            return AjaxResult.error("密码长度不能少于6位");
        }

        String phone = map.get("phone");
        String password = map.get("password");
        WnjkUser user = wnjkUserService.findByPhone(phone);

        if (user == null) {
            return AjaxResult.error("用户不存在");
        }
        if (!password.equals(user.getPassword())) {
            return AjaxResult.error("密码错误");
        }

        String jwtToken = generateJwtToken(user);
        try {
            stringRedisTemplate.opsForValue().set("token-" + user.getPhone(), jwtToken, jwtExpiration / 1000, TimeUnit.SECONDS);
        } catch (Exception e) {
            return AjaxResult.error("存储 token 失败，请稍后重试");
        }

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("phone", user.getPhone());
        userInfo.put("username", user.getNickname());

        Map<String, Object> map2 = new HashMap<>();
        map2.put("token", jwtToken);
        map2.put("userInfo", userInfo);
        return AjaxResult.success(map2);
    }

    @GetMapping("/validate-token")
    public AjaxResult validateToken(@RequestHeader("Authorization") String token) {
        if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
            return AjaxResult.error("未提供token");
        }

        token = token.substring(7); // 去掉 "Bearer " 前缀
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String redisToken = stringRedisTemplate.opsForValue().get("token-" + claims.get("phone"));
            if (redisToken == null || !redisToken.equals(token)) {
                return AjaxResult.error("token无效或已过期");
            }
            Map<String, Object> result = new HashMap<>();
            result.put("userId", claims.get("userId"));
            result.put("phone", claims.get("phone"));
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("token无效或已过期");
        }
    }

    @GetMapping("/info")
    public AjaxResult info() {
        // 从 ThreadLocal 中获取当前用户的手机号
        String phone = AuthenticationContextHolder.getContext();
        if (phone == null) {
            return AjaxResult.error("用户未登录");
        }

        // 查询用户信息
        WnjkUser user = wnjkUserService.findByPhone(phone);
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }

        // 返回用户信息
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        return AjaxResult.success(result);
    }

    private String generateJwtToken(WnjkUser user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        claims.put("phone", user.getPhone());
        return JwtUtil.createJWT(user.getId().toString(), claims, jwtExpiration);
    }
}